import { isObj } from "hongshu-view";
import cn from "~/locale/cn";
import en from "~/locale/en";

let TargetLanStr = "";
let TargetLang = null;




/**
 * 获取当前语言
 * @returns 
 */
export const GetLang = ()=>{
    if(TargetLanStr !=""){
        return TargetLanStr;
    }
    let tLang = window.localStorage.getItem("locale");
    if(!tLang){
        tLang = window.navigator.language;
    };
    if(!tLang){
        tLang = "zh-CN";
    };
    if(tLang.indexOf("en") < 0){
        tLang = "zh-CN";
    }else{
        tLang = "en-US";
    };
    TargetLanStr = tLang;
    return TargetLanStr;
};

/**
 * 获取当前语言对象
 * @returns 
 */
export const GetLangObj = ()=>{
    if(TargetLang != null){
        return TargetLang;
    };
    let tLang = GetLang();
    if(tLang == "en-US"){
        TargetLang = en;
    }else{
        TargetLang = cn;
    };
    return TargetLang;
};

/**
 * 根据字段生字段名
 * @param key 
 * @param param 
 * @returns 
 */
export const Locale = (key,param)=>{
    if(!key){
        return "";
    }
    let langObj = GetLangObj();
    let keyArr = key.split(".");
    let index =0;
    for(index = 0;index<keyArr.length;index++){
       
        if(langObj[keyArr[index]]){
            langObj = langObj[keyArr[index]];
        }else{
            break;
        };
    };
    if(index == keyArr.length){
        if(param){
            return replaceWithParam(langObj,param);
        }else{
            return langObj;
        }
        
    }else{
        return key;
    }
 };

  function replaceWithParam(str, param) {
    if (!param) {
        return str;
    };
    if (!isObj) {
        console.warn("本地化传入的pram不是Object对象");
        return str;
    }
    let reg = /\{\w+\}/g;
    let result = str.match(reg);
    result && result.forEach((key) => {

        let field = key.replace("{", "").replace("}", "");
        console.log(key, field)
        if (param.hasOwnProperty(field)) {
            str = str.replace(key,param[field]);
        }
    });
    return str;
}

 /**
  * 生成短路径函数
  * @param prefix 
  * @returns 
  */
 export const ShortLocale = (prefix)=>{   
    return function(key,param){
        return Locale(prefix+"."+key,param);
    }
 }
 
 export const Localelugin = {
    install: (app, options) => {
        //注册全局方法
        app.config.globalProperties.$t = (key,param) => {
          return Locale(key,param);
        };
    }
};

/**
 * 国际化菜单数据
 * @param {*} menuList 
 * @returns 
 */
export const LocaleMenuData = (menuList) =>{
    if(GetLang() == "en-US"){
        transLocalMenuData(menuList);
        return menuList;
    }else{
        return menuList;
    };
   
};

function transLocalMenuData(menuList){
    if(menuList && menuList.length > 0){
        menuList.forEach((item)=>{
            item.name = item.nameEN;
            if(item.child){
                transLocalMenuData(item.child);
            }
        });
    };
    
};
